package com.demo.gateway.routes.filters;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.cloud.gateway.filter.FilterDefinition;
import org.springframework.stereotype.Component;

/**
 * @author: demo
 * @date: 2020年6月29日
 * @Document : 过滤器工厂类
 */
@Component
public class FilterFactory {
   private  static final  String  REDIS_RATE_FILTER="RequestRateLimiter";
   private  static final  String  HYSTRIX_FILTER="Hystrix";
	/**
	 * redis 限速过滤器 单一 ip+api 每秒最大访问3次
	 * 
	 * @return
	 */
	public FilterDefinition getRedisGatewayFilter() {
		FilterDefinition filterDefinition = new FilterDefinition();
		Map<String, String> filterParams = new HashMap<>(8);
		// 名称是固定的，spring gateway会根据名称找对应的FilterFactory
		filterDefinition.setName(REDIS_RATE_FILTER);
		// 每秒最大访问次数
		filterParams.put("redis-rate-limiter.replenishRate", "5");
		// 令牌桶最大容量
		filterParams.put("redis-rate-limiter.burstCapacity", "20");
		// 限流策略(#{@BeanName})
		filterParams.put("key-resolver", "#{@apiAndIpKeyResolver}");
		filterParams.put("description", "限速过滤规则");
		// 自定义限流器(#{@BeanName})
		// filterParams.put("rate-limiter", "#{@redisRateLimiter}");
		filterDefinition.setArgs(filterParams);
		return filterDefinition;
	}
	
	/**
	 * 熔断策略配置
	 * @return
	 */
	public FilterDefinition  getHystrixGatewayFilter() {
		FilterDefinition filterDefinition = new FilterDefinition();
		filterDefinition.setName(HYSTRIX_FILTER);
		Map<String, String> filterParams = new HashMap<>(8);
		//默认熔断策略
		filterParams.put("name", "default");
		//默认跳转url
		filterParams.put("fallbackUri", "forward:/fallback");
		filterParams.put("description", "熔断过滤规则");
		filterDefinition.setArgs(filterParams);
		return  filterDefinition;
	}

	/**
	 * 转换为filtesList
	 * 
	 * @param definitions
	 * @return
	 */
	public List<FilterDefinition> asFiltersList(FilterDefinition... definitions) {
		return Arrays.asList(definitions);
	}
}
